import { ReactComponentExt } from '@helpers/ReactExt'
import utils from '@helpers/utils'
import { BaseProps } from '@store/store'
import { Icon, Menu } from 'antd'
import { ClickParam } from 'antd/lib/menu'
import * as React from 'react'
import { Link, withRouter } from 'react-router-dom'
import { routeConfigs } from 'routers/route'
import './asideMenu.less'

const { Item } = Menu

// tslint:disable-next-line:no-empty-interface
export interface AsideMenuProps extends BaseProps {
}

interface AsideMenuState {
  current: string
}

class AsideMenu extends ReactComponentExt<AsideMenuProps, AsideMenuState> {

  public state = {
    current: 'index'
  }

  public init(): void {
    this.handleClick = this.handleClick.bind(this)
  }

  public componentDidMount() {
    const { location } = this.props
    this.setState({ current: this.normalizeKey(location!.pathname) })
  }

  public render() {
    const { current } = this.state
    return (
      <Menu
        theme='dark'
        defaultSelectedKeys={['index']}
        onClick={this.handleClick}
        selectedKeys={[current]}
        mode='inline'
        className='asideMenuPage'
      >
        {
          this.genMenuList()
        }
      </Menu>
    )
  }

  private normalizeKey(path: string): string {
    let key = path.slice(1).split('/')[0]
    if (path === '/') {
      key = 'index'
    } else {
      key = utils.camelizeKey(key)
    }
    return key

  }

  private genMenuList() {
    const list = []
    for (const r of routeConfigs) {
      const { path, title, isNav } = r
      if (!isNav) {
        continue
      }
      const key = this.normalizeKey(path)
      list.push(
        <Item key={key}>
          <Icon type='home' />
          <Link to={path}>{title}</Link>
        </Item>
      )
    }
    return list
  }

  private handleClick(e: ClickParam) {
    this.setState({ current: e.key })
  }

}

export default withRouter((props) => {
  return <AsideMenu {...props} />
})
